
function Zopt = GH_Instr(XC,Z,A)

XC = Z * (Z \ XC); % first-stage fitted values

Zgh1 = zeros(size(XC));
Zgh2 = Zgh1;
for j = 1:size(XC,1)
    Zgh1(j,:) = A(j,:) * (XC(j,:) - XC) / (sum(A(j,:)) - 1); % mean attribute distance to other candidates in district
    Zgh2(j,:) = A(j,:) * (XC(j,:) - XC).^2 / (sum(A(j,:)) - 1); % mean squared attribute distance
end

Zopt = [Z,Zgh1,Zgh2];

    

